package Action;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.jdom.JDOMException;

import Beans.Package;
import Beans.WxUser;
import DAO.AgentDao;
import DAO.PackageDao;
import DAO.WxUserDao;
import Utils.CheckPhoneHelper;
import Utils.GenerateRandNumHelper;
import Utils.SendSMSHelper;

import com.github.x0001.weixin.WeiXin;
import com.github.x0001.weixin.vo.recv.WxRecvEventMsg;
import com.github.x0001.weixin.vo.recv.WxRecvMsg;
import com.github.x0001.weixin.vo.recv.WxRecvTextMsg;
import com.github.x0001.weixin.vo.send.WxSendMsg;
import com.github.x0001.weixin.vo.send.WxSendTextMsg;
import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class WxUserAction extends ActionSupport {
	private static final String TOKEN = "token";

	private static final String MENU = "请您输入对应字母\nA.查件.\nB.寄件.\nC.历史包裹查询.\nD.注册.";
	private static final String A_Unregistered = "您还未注册，只能通过\n运单号查询快件信息\nA2.通过运单号查件.";
	private static final String A_Registered = "请输入对应字母与数字\nA1.查询邮宝系统中是\n否有您的未取包裹\nA2.通过运单号查件.";
	private static final String A1_Unregistered = "您的手机号还未绑定，请先绑定您的手机号码。";
	private static final String A1_Registered = "没有您的未取包裹信息.";
	private static final String A2_Unregistered = "请输入S+快递单号查询您的包裹，例如\nS022655267317";
	private static final String B_Unregistered = "【P1】大学城福建师大：153-9453-8486\n请拨打相应网点热线.";
	private static final String C_Registered = "未查询到历史包裹记录.";
	private static final String D_UnregisteredPhone = "请输入您的手机号码.";
	private static final String D_UnregisteredCheckCode = "校验码已发送到您的手\n机，请回复6位校验码\n【如未收到，请在60秒\n后重新输入手机号码】";
	private static final String D_Registered = "绑定成功，谢谢支持！";

	private static int random = 1;

	private WxUser wxUser = null;
	// private User user = null;
	// private Agent agent = null;

	private String signature;
	private String timestamp;
	private String nonce;
	private String echostr;
	private String checkCode = null;
	private String phoneNumber;
	// private boolean binding = false;

	private StringBuffer buffer = null;

	private PrintWriter pw;

	WxUserDao wxUserDao = new WxUserDao();
	PackageDao packageDao = new PackageDao();
	AgentDao agentDao = new AgentDao();
	// UserDao userDao = new UserDao();

	List<WxUser> wxUsers;
	List<Package> packages;

	// List<User> users;
	// List<Agent> agents;

	public String execute() throws Exception {

		HttpServletRequest req = ServletActionContext.getRequest();
		HttpServletResponse resp = ServletActionContext.getResponse();

		// 首次微信服务器连接
		if (null != timestamp && null != nonce && null != echostr
				&& null != signature) {
			if (WeiXin.access(TOKEN, signature, timestamp, nonce)) {
				resp.setHeader("Content-type", "text/html;charset=UTF-8");
				pw = resp.getWriter();
				pw.write(echostr);
				pw.close();
			}
			pw.write("");
			pw.flush();
			pw.close();
		}
		try {
			WxRecvMsg msg = WeiXin.recv(req.getInputStream());
			WxSendMsg sendMsg = WeiXin.builderSendByRecv(msg);
			System.out.println(msg);
			// 事件推送
			if (msg instanceof WxRecvEventMsg) {
				WxRecvEventMsg m = (WxRecvEventMsg) msg;
				String event = m.getEvent();
				if ("subscribe".equals(event)) {
					String content = MENU;
					sendMsg = new WxSendTextMsg(sendMsg, content);
					WeiXin.send(sendMsg, resp.getOutputStream());
				}
				WeiXin.send(eventHandling(sendMsg, msg), resp.getOutputStream());// 调用事件处理函数
			}
			// 根据用户推送过来的文本信息返回菜单(文本信息)/音乐/新闻信息
			else if (msg instanceof WxRecvTextMsg) {
				WeiXin.send(textHandling(sendMsg, msg), resp.getOutputStream());// 调用文本处理函数
			} else {// 用户推送过来的为非文本信息,返回菜单
				String content = MENU;
				sendMsg = new WxSendTextMsg(sendMsg, content);
				WeiXin.send(sendMsg, resp.getOutputStream());
			}
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 事件消息处理
	 * 
	 * @param sendMsg
	 * @param msg
	 * @return
	 */
	public WxSendMsg eventHandling(WxSendMsg sendMsg, WxRecvMsg msg) {
		WxRecvEventMsg m = (WxRecvEventMsg) msg;

		// users = userDao.getUserByWxID(m.getFromUser());
		// if (users.size() > 0) {
		// user = users.get(0);
		// binding = true;
		// }
		wxUsers = wxUserDao.getWxUserByNumber(m.getFromUser());
		if (wxUsers.size() > 0) {
			wxUser = wxUsers.get(0);
			checkCode = wxUser.getCheckCode();
		}

		String key = m.getEventKey();

		if ("query".equals(key)) {
			sendMsg = new WxSendTextMsg(sendMsg, unTakeHanding());
		} else if ("ubindquery".equals(key)) {
			String content = A2_Unregistered;
			sendMsg = new WxSendTextMsg(sendMsg, content);
		} else if ("send".equals(key)) {
			String content = B_Unregistered;
			sendMsg = new WxSendTextMsg(sendMsg, content);
		} else if ("history".equals(key)) {
			sendMsg = new WxSendTextMsg(sendMsg, historyHanding());
		} else if ("bind".equals(key)) {
			String content = null;
			if (wxUsers.size() > 0 && wxUser.getFlag() == 1) {
				content = "您已注册，悟空别闹！";
			} else {
				content = D_UnregisteredPhone;
			}
			sendMsg = new WxSendTextMsg(sendMsg, content);
		}
		// else if (text.startsWith("s") || text.startsWith("S")) {
		// sendMsg = new WxSendTextMsg(sendMsg, parcelIdHanding(text));
		// }
		// else if (CheckPhoneHelper.isMobileNO(text)) {
		// sendMsg = new WxSendTextMsg(sendMsg, phoneHanding(text,
		// m.getFromUser()));
		// } else if (text.length() == 6 && size > 0 && checkCode.equals(text))
		// {
		// if (wxUser.getBinding() != 0) {
		// String content = "您已注册，悟空别闹！";
		// sendMsg = new WxSendTextMsg(sendMsg, content);
		// } else {
		// wxUser.setBinding(1);
		// wxUserDao.edit(wxUser);
		// String content =
		// "尊敬的用户，已绑定好您的手机号码。谢谢您对邮宝的支持。\n请输入相应字母，以获取相关服务。\nA.查件;\nB.寄件;\nC.历史包裹查询;\nD.绑定手机号码【更方便您的使用】。";
		// sendMsg = new WxSendTextMsg(sendMsg, content);
		// }
		// }
		else {// 不在选择范围的选项返回菜单
			String content = MENU;
			sendMsg = new WxSendTextMsg(sendMsg, content);
		}
		return sendMsg;
	}

	/**
	 * 文本消息处理
	 * 
	 * @param sendMsg
	 * @param msg
	 * @return
	 */
	public WxSendMsg textHandling(WxSendMsg sendMsg, WxRecvMsg msg) {
		WxRecvTextMsg m = (WxRecvTextMsg) msg;

		// agents=agentDao.getAllAgent();
		// agent=agents.get(0);
		//
		// users = userDao.getUserByWxID(m.getFromUser());
		// if (users.size() > 0) {
		// user = users.get(0);
		// binding = true;
		// }
		wxUsers = wxUserDao.getWxUserByNumber(m.getFromUser());
		if (wxUsers.size() > 0) {
			wxUser = wxUsers.get(0);
			checkCode = wxUser.getCheckCode();
		}

		String text = m.getContent();
		if (null != text)
			text = text.trim();

		Set<String> keyworkds = new HashSet<String>();
		keyworkds.add("M");
		keyworkds.add("菜单");
		keyworkds.add("menu");
		keyworkds.add("m");

		if (keyworkds.contains(text)) {
			// 如果text值为M返回菜单文本信息
			String content = MENU;
			sendMsg = new WxSendTextMsg(sendMsg, content);

		} else if ("A".equals(text) || "a".equals(text)) {
			if (wxUsers.size() > 0 && wxUser.getFlag() == 1) {
				String content = A_Registered;
				sendMsg = new WxSendTextMsg(sendMsg, content);
			} else {
				String content = A_Unregistered;
				sendMsg = new WxSendTextMsg(sendMsg, content);
			}
		} else if ("A1".equals(text) || "a1".equals(text)) {
			sendMsg = new WxSendTextMsg(sendMsg, unTakeHanding());
		} else if ("A2".equals(text) || "a2".equals(text)) {
			String content = A2_Unregistered;
			sendMsg = new WxSendTextMsg(sendMsg, content);
		} else if ("B".equals(text) || "b".equals(text)) {
			String content = B_Unregistered;
			sendMsg = new WxSendTextMsg(sendMsg, content);
		} else if ("C".equals(text) || "c".equals(text)) {
			sendMsg = new WxSendTextMsg(sendMsg, historyHanding());
		} else if ("D".equals(text) || "d".equals(text)) {
			String content = null;
			if (wxUsers.size() > 0 && wxUser.getFlag() == 1) {
				content = "您已注册，悟空别闹！";
			} else {
				content = D_UnregisteredPhone;
			}
			sendMsg = new WxSendTextMsg(sendMsg, content);
		} else if (text.startsWith("s") || text.startsWith("S")) {
			sendMsg = new WxSendTextMsg(sendMsg, parcelIdHanding(text));
		} else if (text.length() == 11 && CheckPhoneHelper.isMobileNO(text)) {
			sendMsg = new WxSendTextMsg(sendMsg, phoneHanding(text,
					m.getFromUser()));
		}
		// else if (CheckMailHelper.isMail(text)) {
		// String content = null;
		// if (user.getName() == null || "".equals(user.getName())) {
		// if (binding) {
		// user.setName(text);
		// userDao.edit(user);
		// content = "信息完善成功！";
		// } else {
		// content = "请先注册！";
		// }
		// } else {
		// content = "您已完善过个人信息！";
		// }
		// sendMsg = new WxSendTextMsg(sendMsg, content);
		// }
		else if (text.length() == 6 && wxUsers.size() > 0
				&& checkCode.equals(text)) {
			if (wxUser.getFlag() == 1) {
				String content = "您已注册，悟空别闹！";
				sendMsg = new WxSendTextMsg(sendMsg, content);
			} else {
				wxUser = wxUsers.get(0);
				wxUser.setFlag(1);
				wxUserDao.edit(wxUser);
				// users = userDao.getAllUserPhoneNum(wxUser.getPhone());
				// if (users.size() > 0) {
				// User u = users.get(0);
				// u.setWxID(wxUser.getNumber());
				// userDao.edit(u);
				// } else {
				// User u = new User();
				// u.setWxID(wxUser.getNumber());
				// u.setMobileNum(wxUser.getPhone());
				// u.setAgent(agent);
				// u.setSex("2");
				// u.setStatus("1");
				// userDao.save(u);
				// }
				String content = D_Registered;
				sendMsg = new WxSendTextMsg(sendMsg, content);
			}
		} else {// 不在选择范围的选项返回菜单
			String content = MENU;
			sendMsg = new WxSendTextMsg(sendMsg, content);
		}
		return sendMsg;
	}

	/**
	 * 未取包裹处理
	 * 
	 * @return
	 */
	public String unTakeHanding() {
		String content = null;
		if (wxUsers.size() > 0
				&& (wxUser.getFlag() == 1 || wxUser.getFlag() == 2)) {
			packages = packageDao.getUnTakenPackageDetailByPhone(wxUser
					.getPhone());
			if (packages.size() > 0) {
				buffer = new StringBuffer();
				buffer.append("您共有 " + packages.size() + "件未取包裹：\n\n");
				for (int i = 0; i < packages.size(); i++) {
					Package p = packages.get(i);
					buffer.append("包裹" + (i + 1) + "信息：\n");
					buffer.append("运单号码：" + p.getParcelId() + "\n");
					buffer.append("快递公司：" + p.getCourier().getCompany() + "\n");
					buffer.append("取件码：" + p.getCheckCode() + "\n");
					buffer.append("物流信息：\n");
					buffer.append(p.getStoreTime() + "存入"
							+ p.getTerminal().getBranch().getBranchName()
							+ p.getTerminal().getName() + "。\n\n");
				}
				content = buffer.toString();
			} else {
				content = A1_Registered;
			}
		} else {
			content = A1_Unregistered;
		}
		return content;
	}

	/**
	 * 历史包裹处理
	 * 
	 * @return
	 */
	public String historyHanding() {
		String content = null;
		if (wxUsers.size() > 0
				&& (wxUser.getFlag() == 1 || wxUser.getFlag() == 2)) {
			packages = packageDao.getHistoryPackageByPhone(wxUser.getPhone());
			if (packages.size() > 0) {
				buffer = new StringBuffer();
				buffer.append("您共有 " + packages.size() + "件包裹存放过\n邮宝智能快件箱：\n\n");
				for (int i = 0; i < packages.size() && i < 5; i++) {
					Package p = packages.get(i);
					buffer.append("包裹" + (i + 1) + "信息：\n");
					buffer.append("运单号码：" + p.getParcelId() + "\n");
					buffer.append("快递公司：" + p.getCourier().getCompany() + "\n");
					buffer.append("存放地址： "
							+ p.getTerminal().getBranch().getBranchName()
							+ "网点" + p.getTerminal().getName() + "\n");
					buffer.append("存入时间：" + p.getStoreTime() + "\n");
					buffer.append("取出时间：" + p.getGetTime() + "\n\n");
				}
				buffer.append("更多历史包裹详情请登录友宝官网查询");
				content = buffer.toString();
			} else {
				content = C_Registered;
			}
		} else {
			content = A_Unregistered;
		}
		return content;
	}

	/**
	 * 处理运单号
	 * 
	 * @param text
	 * @return
	 */
	public String parcelIdHanding(String text) {
		String content = null;
		boolean b = false;
		boolean a = false;
		if (wxUsers.size() > 0) {
			if (wxUser.getFlag() == 2) {
				b = true;
			}
		}
		packages = packageDao.getPackageByParcelID((text.substring(1)).trim());
		if (packages.size() > 0) {
			buffer = new StringBuffer();
			buffer.append("您共有 " + packages.size() + "件包裹信息：\n\n");
			for (int i = 0; i < packages.size() && i < 5; i++) {
				Package p = packages.get(i);
				if (wxUser!=null&&wxUser.getPhone().equals(p.getUserPhone())) {
					a = true;
				}
				buffer.append("包裹" + (i + 1) + "信息：\n");
				buffer.append("运单号码：" + p.getParcelId() + "\n");
				buffer.append("快递公司：" + p.getCourier().getCompany() + "\n");
				if (a || b) {
					buffer.append("取件码：" + p.getCheckCode() + "\n");
					buffer.append("手机号码：" + p.getUserPhone() + "\n");
				}
				buffer.append("物流信息：\n");
				buffer.append(p.getStoreTime() + "  已存入"
						+ p.getTerminal().getBranch().getBranchName()
						+ p.getTerminal().getName() + p.getBoxId() + "号柜。\n");
				if (p.getGetTime() != null) {
					buffer.append(p.getGetTime() + "已取出。\n\n");
				} else {
					buffer.append("包裹未取。\n\n");
				}
			}
			buffer.append("更多包裹详情请登录友宝官网查询");
			content = buffer.toString();
		} else {
			content = "在我司的快件箱内未查询到您的包裹信息。";
		}
		return content;
	}

	/**
	 * 管理员查询
	 * 
	 * @param text
	 * @return
	 */
	public String adminSearch(String text) {
		String content = null;
		packages = packageDao.getPackageDetailByPhone(text);
		if (packages.size() > 0) {
			buffer = new StringBuffer();
			buffer.append("您共有 " + packages.size() + "件包裹信息：\n\n");
			for (int i = 0; i < packages.size() && i < 5; i++) {
				Package p = packages.get(i);
				buffer.append("包裹" + (i + 1) + "信息：\n");
				buffer.append("运单号码：" + p.getParcelId() + "\n");
				buffer.append("快递公司：" + p.getCourier().getCompany() + "\n");
				buffer.append("取件码：" + p.getCheckCode() + "\n");
				buffer.append("物流信息：\n");
				buffer.append(p.getStoreTime() + "  已存入"
						+ p.getTerminal().getBranch().getBranchName()
						+ p.getTerminal().getName() + p.getBoxId() + "号柜。\n");
				if (p.getGetTime() != null) {
					buffer.append(p.getGetTime() + "已取出。\n\n");
				} else {
					buffer.append("包裹未取。\n\n");
				}
			}
			buffer.append("更多包裹详情请登录友宝官网查询");
			content = buffer.toString();
		} else {
			content = "在我司的快件箱内未查询到您的包裹信息。";
		}
		return content;
	}

	/**
	 * 处理电话号码
	 * 
	 * @param text
	 * @param number
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public String phoneHanding(String text, String number) {
		Date date = new Date();
		String content = null;
		if (wxUsers.size() > 0 && wxUser.getFlag() == 1) {
			// if (wxUser.getFlag() == 1) {
			// content = adminSearch(text);
			// } else {
			content = "您已注册，悟空别闹！";
			// }
		} else if (wxUsers.size() > 0 && wxUser.getFlag() == 2) {
			content = adminSearch(text);
		} else if (wxUsers.size() > 0
				&& (date.getMinutes() - wxUser.getTime().getMinutes()) == 0) {
			content = "校验码已发送过，请输入校验码！";
		} else if (wxUsers.size() > 0
				&& (date.getMinutes() - wxUser.getTime().getMinutes()) > 0) {
			phoneNumber = text;
			checkCode = wxUser.getCheckCode();
			wxUser.setTime(new Timestamp(date.getTime()));
			wxUserDao.edit(wxUser);
			sendMessage();
			content = D_UnregisteredCheckCode;
		} else {
			phoneNumber = text;
			checkCode = GenerateRandNumHelper.generate(6);
			wxUser = new WxUser();
			wxUser.setPhone(phoneNumber);
			wxUser.setNumber(number);
			wxUser.setCheckCode(checkCode);
			wxUser.setAgent(agentDao.getAgentById(1));
			wxUserDao.save(wxUser);
			sendMessage();
			content = D_UnregisteredCheckCode;
		}
		return content;
	}

	/**
	 * 随机发送短信
	 */
	public void sendMessage() {
		random += 1;
		switch (random % 6) {
		case 0:
			SendSMSHelper.send("邮宝让您畅享“自由”生活！您的校验码为：" + checkCode,
					phoneNumber);
			break;
		case 1:
			SendSMSHelper.send("友宝——不只是国标制定者。您的校验码为：" + checkCode,
					phoneNumber);
			break;
		case 2:
			SendSMSHelper.send("让包裹存一会儿，让自由飞一会儿。您的校验码为：" + checkCode,
					phoneNumber);
			break;
		case 3:
			SendSMSHelper.send("存的是包裹，取的是自由。您的校验码为：" + checkCode,
					phoneNumber);
			break;
		case 4:
			SendSMSHelper.send(
					"Whenever you come,I will be here waiting for you.您的校验码为："
							+ checkCode, phoneNumber);
			break;
		case 5:
			SendSMSHelper.send("收件用邮宝，“收” easy。您的校验码为：" + checkCode,
					phoneNumber);
			break;
		default:
			SendSMSHelper.send("您的校验码为：" + checkCode, phoneNumber);
		}
	}

	public WxUser getWxUser() {
		return wxUser;
	}

	public void setWxUser(WxUser wxUser) {
		this.wxUser = wxUser;
	}

	public String getSignature() {
		return signature;
	}

	public void setSignature(String signature) {
		this.signature = signature;
	}

	public String getTimestamp() {
		return timestamp;
	}

	public void setTimestamp(String timestamp) {
		this.timestamp = timestamp;
	}

	public String getNonce() {
		return nonce;
	}

	public void setNonce(String nonce) {
		this.nonce = nonce;
	}

	public String getEchostr() {
		return echostr;
	}

	public void setEchostr(String echostr) {
		this.echostr = echostr;
	}

	public String getPhoneNumber() {
		return phoneNumber;
	}

	public void setPhoneNumber(String phoneNumber) {
		this.phoneNumber = phoneNumber;
	}

	public PrintWriter getPw() {
		return pw;
	}

	public void setPw(PrintWriter pw) {
		this.pw = pw;
	}

	public List<WxUser> getWxUsers() {
		return wxUsers;
	}

	public void setWxUsers(List<WxUser> wxUsers) {
		this.wxUsers = wxUsers;
	}

}
